<template>
    <Layout>
        <Form ref="queryForm" :label-width="120" :loading="pageStatus.baseLoading">
            <Row class="query-form">
                <Col span="8">
				  <FormItem label="车辆所在公司：" prop="workOrgId">
				    <cascaderDom class="query-form-el" style="padding-top: 4px; width: 100%;" ref="carOrg"
				    	@setOrgInfo="setOrgId" @setOrgName="setOrgName"
				    	:currentOrgId="dataToQuery.workOrgId" :currentOrgName="dataToQuery.orgName"
				    	:orgTree="true"></cascaderDom>
				  </FormItem>
                </Col>
                <Col span="8">
					<FormItem label='年份：' prop='year'>
					    <DatePicker class="query-form-el" placeholder="请选择年份" v-model='dataToQuery.yearDate' type="year"></DatePicker>
					</FormItem>
                </Col>
				<Col span="8">
					<FormItem label='季度：' prop='quarter'>
						<Select v-model="dataToQuery.quarter"
						        filterable
								clearable
								placeholder="请选择季度">
						    <Option v-for="(option, index) in quarterList" :value="option.value" :key="index">{{option.label}}</Option>
						</Select>
					</FormItem>
				</Col>
            </Row>
			<Row class="query-form">
				<Col span="8" offset="16">
					<Button @click="reset" class="ivu-btn-reset">重置</Button>
					<Button type="primary" class="ivu-btn-query" icon="md-search"  @click="query">查询</Button>
				</Col>
			</Row>
			<Row class="query-form">
				<Col span="24">
					<Button type="primary" class="ivu-btn-add"   icon="md-cloud-download" :loading="buttonLoading" @click="exportFormSubmit">导出</Button>
				</Col>
			</Row>
        </Form>
		<Table ref='table' :height="tableHeight" :row-class-name="rowClassName" no-data-text="没有查询到相关数据!" @on-selection-change = 'getSelectRows' :loading='pageStatus.loading || pageStatus.baseLoading'
		       border :columns="columns1"  :data="dataTable" >
		</Table>
		<Row style="margin-right:10px;">
		  <Col span="24" >
		    <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
		  </Col>
		</Row>
    </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {sessionStorage} from '@/common/cacheUtils.js';
import {formatDate,createFormAndSubmit} from '@/tools/index'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import cascaderDom from "../../../../components/cascader-dom.vue"
    export default {
        components: {cascaderDom},
        data() {
            return {
				...this.createCommonDataField(),
				quarterList:[{
									value: '1',
									label: '一季度'
								},
								{
									value: '2',
									label: '二季度'
								},
								{
									value: '3',
									label: '三季度'
								},
								{
									value: '4',
									label: '四季度'
								}],
                columns1: [
                    {
                        title: "序号",
                        width: 80,
                        align: "center",
                        fixed: 'left',
                        render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }
                    },
                    {
                        minWidth: 200,
                        title: '车辆所在单位名称',
                        align: 'center',
						fixed: 'left',
                        key: 'workOrgName',
                    },
					{
						title: '车牌号',
						minWidth: 150,
						align: 'center',
						fixed: 'left',
						key: 'plateNumber',
					},
					{
					    minWidth: 100,
					    title: '车辆违章次数',
					    align: 'center',
					    key: 'violationCarNum',
					}
                ],
				buttonLoading:false,
				tableHeight:10,
				queryUrl:Api.getCarStatistics,
            }
        },
		async mounted() {
		  this.setTableHeight();
		  this.query();
		},
        methods: {
			...pageCommonFunction,
			setOrgId(data) {
				this.dataToQuery.workOrgId = data[data.length - 1];
			},
			setOrgName(data) {
				this.dataToQuery.orgName = data;
			},
			query() {
				if(!this.dataToQuery.yearDate) {
				    this.dataToQuery.yearDate = new Date();
				}
				if(this.dataToQuery.yearDate) {
				  this.dataToQuery.year = this.dataToQuery.yearDate.getFullYear();
				}
				this.dataToQuery.orgId = sessionStorage('userId').getObject('userId').companyId,
				this.queryAjax();
			},
			reset() {
				this.dataToQuery = {}
				this.query()
			},
			exportFormSubmit() {
				this.buttonLoading=true
				let orgId = sessionStorage('userId').getObject('userId').companyId
				let data = {
				    orgId:orgId,
				};
				data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
				this.$http.get(Api.exportCarStatistics, {
				    params:data,
				    responseType: 'blob'      //告诉服务器我们需要的响应格式
				}).then((res) => {
				    const aLink = document.createElement("a");
				    let blob = new Blob([res.data], {
				        type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
				    });
				    aLink.href = URL.createObjectURL(blob)
				    aLink.download = "交通违章车辆统计("+ this.formatDate(new Date(), "yyyy-MM-dd")+ ").xlsx" //标题
				    aLink.click()
				    document.body.appendChild(aLink)
				    this.buttonLoading=false
				})
			},
			formatDate(date, fmt) {
			    if (/(y+)/.test(fmt)) {
			        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
			    }
			    let o = {
			        'M+': date.getMonth() + 1,
			        'd+': date.getDate(),
			        'h+': date.getHours(),
			        'm+': date.getMinutes(),
			        's+': date.getSeconds()
			    };
			    for (let k in o) {
			        if (new RegExp(`(${k})`).test(fmt)) {
			            let str = o[k] + '';
			            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
			        }
			    }
			    return fmt;
			},
			padLeftZero(str) {
				return ('00' + str).substr(str.length);
			},
			getSelectRows(rows) {
				this.deleteRows = rows;
			},
        }
    }
</script>

<style lang='css' scoped>
	@import '../../../../index.css';
</style>